#!/bin/bash

if [ $# -ge 1 ]; then

  if [ $# -ge 3 ]; then
    echo "too many arguments."
    echo "usage: $0 prefix [nCpu]"
    exit
  fi

  nCpu=1
  if [ $# -eq 2 ]; then nCpu=$2; fi
  prefix=$1

  # configure.ac
  if [ ! -e configure.ac ]; then
    echo 'AC_INIT([ckon], [0.0])' >> configure.ac
    echo 'm4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])' >> configure.ac
    echo 'AC_CONFIG_AUX_DIR(config)' >> configure.ac
    echo 'm4_pattern_allow([AM_PROG_AR])' >> configure.ac
    echo 'm4_ifdef([AM_PROG_AR], [AM_PROG_AR])' >> configure.ac
    echo 'AM_INIT_AUTOMAKE([-Wall no-define])' >> configure.ac
    echo 'AC_PROG_CXX' >> configure.ac
    echo 'AX_BOOST_BASE([1.50])' >> configure.ac
    echo 'AX_BOOST_SYSTEM' >> configure.ac
    echo 'AX_BOOST_FILESYSTEM' >> configure.ac
    echo 'AX_BOOST_REGEX' >> configure.ac
    echo 'AX_BOOST_PROGRAM_OPTIONS' >> configure.ac
    echo 'LIBCURL_CHECK_CONFIG' >> configure.ac
    echo 'AC_CONFIG_FILES([Makefile])' >> configure.ac
    echo 'AC_OUTPUT' >> configure.ac
  fi

  if [ ! -e Makefile.am ]; then
    echo 'AUTOMAKE_OPTIONS = foreign subdir-objects -Wall' >> Makefile.am
    echo 'ACLOCAL_AMFLAGS = ${ACLOCAL_FLAGS} -I m4' >> Makefile.am
    echo 'AM_CPPFLAGS = $(BOOST_CPPFLAGS)' >> Makefile.am
    echo 'AM_CPPFLAGS += @LIBCURL_CPPFLAGS@' >> Makefile.am
    echo 'bin_PROGRAMS = ckon' >> Makefile.am
    echo 'ckon_LDFLAGS = $(BOOST_LDFLAGS) -lstdc++' >> Makefile.am
    echo 'ckon_LDFLAGS += $(BOOST_SYSTEM_LIB)' >> Makefile.am
    echo 'ckon_LDFLAGS += $(BOOST_FILESYSTEM_LIB)' >> Makefile.am
    echo 'ckon_LDFLAGS += $(BOOST_REGEX_LIB)' >> Makefile.am
    echo 'ckon_LDFLAGS += $(BOOST_PROGRAM_OPTIONS_LIB)' >> Makefile.am
    echo 'ckon_LDFLAGS += @LIBCURL@' >> Makefile.am
    echo 'ckon_SOURCES =' >> Makefile.am
    for file in `find . -type f -name "*.h" -o -name "*.cc"`; do
      echo "ckon_SOURCES += $file" >> Makefile.am
    done
  fi

  autoreconf --force --install
  mkdir -v build
  cd build
  boostopts='--with-boost --with-boost-filesystem --with-boost-system'
  boostopts=$boostopts' --with-boost-regex --with-boost-program-options'
  ../configure --prefix=$prefix $boostopts
  make -j $nCpu CXXFLAGS="-Wall -Werror"
  make install

  echo "===> ckon build done."

else
  echo "usage: $0 prefix [nCpu]"
  echo "prefix = install dir"
  echo "nCpu = #cpu's for parallel build (-j) [default=1]"
fi
